<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2019-11-27
 * Time: 11:24
 */

namespace app\api\service;

use app\api\model\Member;
use app\api\model\ProjectHatch;
use app\api\model\ProjectHatchCommentOrder;
use app\api\model\ProjectHatchLook;
use app\api\model\ProjectHatchLookOrder;
use app\api\model\ProjectHatchOrder;
use app\api\model\User;
use app\lib\enum\ScopeEnum;
use app\lib\exception\ForbiddenException;
use app\lib\exception\ParameterException;
use app\lib\exception\TokenException;
use think\Exception;
use think\facade\Request;
use think\facade\Cache;

class Token
{
    /**
     * 生成token值
     */
    public function generateToken()
    {
        //32字符组成的一组随机字符串
        $randChars = getRandChar(32);
        //三组字符串进行md5加密
        $timestamp = $_SERVER['REQUEST_TIME'];
        //salt
        $salt = config('secure.token_salt');
        return md5($randChars.$timestamp.$salt);
    }

    //根据token获取缓存中某一个字段的值
    public static function getCurrentTokenVar($key){
        $token = Request::instance()
            ->header('token');
        $vars = Cache::get($token);
        if(!$vars){
            throw new TokenException();
        }else{
            if(!is_array($vars)){
                $vars = json_decode($vars,true);
            }
            if(array_key_exists($key,$vars)){
                return $vars[$key];
            }else{
                throw new Exception('尝试获取的token变量不存在');
            }
        }
    }

    public static function getCurrentUid(){
        $uid = self::getCurrentTokenVar('uid');
        return $uid;
    }

    //用户和管理员都可以访问的接口权限
    public static function needPrimaryScope(){
        $scope = self::getCurrentTokenVar('scope');
        if($scope)
        {
            if($scope >= ScopeEnum::User)
            {
                return true;
            }
            else{
                throw new ForbiddenException();
            }
        }
        else{
            throw new TokenException();
        }
    }

    //只有用户才可以访问的接口权限
    public static function needExclusiveScope()
    {
        $scope = self::getCurrentTokenVar('scope');
        if($scope)
        {
            if($scope == ScopeEnum::User)
            {
                return true;
            }
            else{
                throw new ForbiddenException();
            }
        }
        else{
            throw new TokenException();
        }

    }

    /**
     * 验证用户token
     */
    public static function verifyToken($token)
    {
        $exist = Cache::get($token);
        if($exist)
        {
            return true;
        }
        else{
            return false;
        }
    }

    // 生成订单编号
    protected static function makeOrderNo()
    {
        $yCode = array('A','B','C','D','E','F','G','H','I','J');
        $orderSn =
            $yCode[intval(date('Y')) - 2020] . strtoupper(dechex(date('m'))) . date('d') .
            substr(time(),-5) . substr(microtime(),2,5) . sprintf('%02d',rand(0,99));
        return $orderSn;
    }

    /**
     * 判断用户是否过期
     */
    public static function judgeMember()
    {
        $uid = self::getCurrentUid();
        $user = User::get($uid);
        if($user['status'] == 0) {
            throw new ParameterException([
                'errorCode' => 10001,
                'msg' => [
                    'member' => '请先进行登录',
                ]
            ]);
        }
        $member = Member::where('user_id',$uid)->find();
        if(!$member) {
            throw new ParameterException([
                'errorCode' => 10002,
                'msg' => [
                    'member' => '请先进行会员认证',
                ]
            ]);
        }
        if($member['status'] == 1) {
            throw new ParameterException([
                'errorCode' => 10003,
                'msg' => [
                    'member' => '请等待会员信息审核通过',
                ]
            ]);
        }
        if($member['status'] == 2) {
            throw new ParameterException([
                'errorCode' => 10004,
                'msg' => [
                    'member' => '会员信息未通过',
                ]
            ]);
        }
        if($member['status'] == 3) {
            throw new ParameterException([
                'errorCode' => 10005,
                'msg' => [
                    'member' => '您已进入系统黑名单',
                ]
            ]);
        }
        if(strtotime($user['member_end_time'].' 23:59:59') < time()) {
            throw new ParameterException([
                'errorCode' => 10006,
                'msg' => [
                    'member' => '会员已过期',
                ]
            ]);
        }
    }

    /**
     * 判断用户是否过期
     */
    public static function judgeMemberOne()
    {
        $uid = self::getCurrentUid();
        $user = User::get($uid);
        if ($user['status'] == 0) {
            throw new ParameterException([
                'errorCode' => 10001,
                'msg' => [
                    'member' => '请先进行登录',
                ]
            ]);
        }
        $member = Member::where('user_id', $uid)->find();
        if (!$member) {
            throw new ParameterException([
                'errorCode' => 10002,
                'msg' => [
                    'member' => '请先进行会员认证',
                ]
            ]);
        }
        if ($member['status'] == 1) {
            throw new ParameterException([
                'errorCode' => 10003,
                'msg' => [
                    'member' => '请等待会员信息审核通过',
                ]
            ]);
        }
        if ($member['status'] == 2) {
            throw new ParameterException([
                'errorCode' => 10004,
                'msg' => [
                    'member' => '会员信息未通过',
                ]
            ]);
        }
        if ($member['status'] == 3) {
            throw new ParameterException([
                'errorCode' => 10005,
                'msg' => [
                    'member' => '您已进入系统黑名单',
                ]
            ]);
        }
    }



        // 判断项目孵化
    public static function judgeProjectHatch()
    {
        $uid = self::getCurrentUid();
        return ProjectHatchOrder::where('status',2)
            ->where('type',1)
            ->where('user_id',$uid)
            ->find();
    }

    // 判断项目孵化评论
    public static function judgeProjectHatchComment()
    {
        $uid = self::getCurrentUid();
        return ProjectHatchCommentOrder::where('status',2)
            ->where('type',1)
            ->where('user_id',$uid)
            ->find();
    }

    // 判断项目孵化查看
    public static function judgeProjectHatchLook($project_hatch_id)
    {
        $uid = self::getCurrentUid();
        self::judgeMemberOne();
        $user = User::get($uid);
        if(strtotime($user['member_end_time'].' 23:59:59') < time() || !$user['member_end_time']) {
            $info = ProjectHatch::get($project_hatch_id);
            if($uid != $info['user_id']) {
                $time = time();
                $where[] = ['user_id','eq',$uid];
                $where[] = ['start_time','elt',$time];
                $where[] = ['end_time','egt',$time];
                $where[] = ['project_hatch_id','egt',$project_hatch_id];
                $info = ProjectHatchLook::where($where)->find();
                if($info) {
                    return ProjectHatchLookOrder::where('status',2)
                        ->where('project_hatch_look_id',$info['id'])
                        ->where('user_id',$uid)
                        ->find();
                } else {
                    return ProjectHatchLookOrder::where('status',2)
                        ->where('type',1)
                        ->where('user_id',$uid)
                        ->find();
                }
            } else {
                return $info;
            }
        } else {
            return $user;
        }

    }
}